const form = document.querySelector("form")
const username = document.querySelector("#username");
const password = document.querySelector("#password");
const usernamespan = document.querySelector("#usernamespan")
const passwordspan = document.querySelector("#passwordspan")
const avrtor=document.querySelector("img")
let userFlag = true;
let passFlag = true;
//账号
username.oninput = function () {
    //当账号的长度在2~16之间的数字,字母,下划线
    const reg = /^\w{2,16}$/g
    if (reg.test(this.value.trim())) {
        usernamespan.innerHTML = "账号符合要求"
        usernamespan.style.color = "green"
        userFlag = true;
    } else {
        usernamespan.innerHTML = "账号的长度在2~16位之间"
        usernamespan.style.color = "red"
        userFlag = false;
    }
}
username.onblur=function(){
    axios({
        method: "post",
        url: "http://localhost:8080/admin/admin/avrtor",
        data: {
            username: username.value,
        }
    })
    .then(res => {
        if (res.data.code == 200) {
             console.log(res.data);
            //将数据渲染到前端
            avrtor.src=res.data.data.avrtor;
            
           
        } else {
            alert(res.data.msg)
            //刷新
            location.reload();
        }
    })
}
//密码
password.oninput = function () {
    //当账号的长度在5~16之间的数字,字母,下划线
    const reg = /^\w{5,16}$/g
    if (reg.test(this.value.trim())) {
        passwordspan.innerHTML = "密码符合要求"
        passwordspan.style.color = "green"
        passFlag = true;
    } else {
        passwordspan.innerHTML = "密码的长度在5~16位之间"
        passwordspan.style.color = "red"
        passFlag = false;
    }
}

form.onsubmit = function (e) {
    //阻止表单提交
    e.preventDefault();
    //获取账号密码
    console.log(userFlag, passFlag);
    if (userFlag && passFlag) {
        // 发送ajax
        axios({
            method: "post",
            url: "http://localhost:8080/admin/admin/login",
            data: {
                ausername: username.value,
                apassword: password.value
            }
        })
            .then(res => {
                if (res.data.code == 200) {
                    //sessionStorage => 会话存储
                    sessionStorage.setItem("token", res.data.token)
                    sessionStorage.setItem("userInfo", JSON.stringify(res.data.data))
                    alert(res.data.msg)
                    //跳转到主页
                    location.href = "./home.html"
                } else {
                    alert(res.data.msg)
                    //刷新
                    location.reload();
                }
            })
    } else {
        alert("账号密码不符合要求")
    }
}